package com.yyj.jan;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {
    public static String httpSend(String data,String urlPath) throws Exception{
        // Set url and data

        JSONObject jsonParam = new JSONObject();
        jsonParam.put("data", data);

        // set post param
        URL url=new URL(urlPath);
        HttpURLConnection httpConn=(HttpURLConnection)url.openConnection();
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        httpConn.setUseCaches(false);
        httpConn.setRequestMethod("POST");
        httpConn.setRequestProperty("Content-Type", "application/json");
        httpConn.setRequestProperty("Connection", "Keep-Alive");
        httpConn.setRequestProperty("Charset", "UTF-8");
        httpConn.connect();
        DataOutputStream dos=new DataOutputStream(httpConn.getOutputStream());

        dos.writeBytes(jsonParam.toString());
        dos.flush();
        dos.close();

        // parse response result
        int resultCode=httpConn.getResponseCode();
        StringBuffer sb=new StringBuffer();
        if(HttpURLConnection.HTTP_OK==resultCode){
            String readLine=new String();
            BufferedReader responseReader=new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
            while((readLine=responseReader.readLine())!=null){
                sb.append(readLine).append("\n");
            }
            responseReader.close();
        }
        return sb.toString();
    }
}
